//returns event-handler, pass options in options object

/*	Accepted Options
	event_type: String - name of event to handle
	valid_elements: Array - Tagname event is handled for, if empty any element is handled
	timer: Milliseconds - if set event will only be handled after time has passed.
*/

(function (sauberfant) {

	var Event_Handler = function (handler, options) {
		
		var that = this;

		
		//actual event handler
		this.handler = handler;

		//set Limitation-Tags or False
		this.valid_elements = options.valid_elements || false;

		//set timer or false
		this.timer = options.timer || false;

		//initialize last executed Time
		this.last_time = 0;

		
		// return proxied event handler
		return  function (event) {		
			that.is_valid_element(event) && that.has_time_passed() && that.handler(event);
		};
		
	};

	Event_Handler.prototype.is_valid_element = function (event) {
		if (!this.valid_elements) {
			return true;
		}

		if (Array.prototype.indexOf) {
			return this.valid_elements.indexOf(event.tagName.toLowerCase()) != -1
		} else {
			var i, len;
			for (i = 0, len = this.valid_elements.length; i < len; i++) {
				if (this.valid_elements[i] == event.tagName.toLowerCase()) {
					return true;
				}
			}
		}
		return false;
	}

	Event_Handler.prototype.has_time_passed = function () {
		if (!this.timer) {
			return true;
		}

		var new_time = (new Date).getTime();
		if (new_time - this.timer > this.last_time) {
			this.last_time = new_time;
			return true;
		}

		return false;

	}

	sauberfant.event_handler = function (handler, options, element) {
		if (!options || (options && !options.event_type)) {
			return false;
		}
		//if element is unset use document as listener
		element = element || window.document;
		
		//add Event to element
		sauberfant.add_event(element, options.event_type, new Event_Handler(handler, options));		
	}

})(sauberfant);